package com.edu.dao.impl;

import com.edu.beans.Book;
import com.edu.beans.Vip;
import com.edu.dao.BookDao;
import com.edu.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class BookDaoImpl implements BookDao {

    QueryRunner qr= new QueryRunner(JdbcUtils.getDataSource());

    @Override
    public int addBook(Book book) {
        try {
            return qr.update("INSERT INTO tb_books VALUES (NULL, ?, ?, ?, ?, NOW())",
                    book.getVip_id(),book.getEnterTime(),book.getExitTime(),book.getHome_id());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Book> getBooksByPhone(String phone) {
        try {
            return qr.query("select * from tb_books where phone = ?",new BeanListHandler<>(Book.class),phone);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int deleteBook(String id) {
        try {
            return qr.update("delete from tb_books where id = ?", id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Book getBookById(String id) {
        try {
            return qr.query("select * from tb_books where id = ?", new BeanHandler<>(Book.class), id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateBook(Book book) {
        try {
            return qr.update("update tb_books set entertime = ?, exittime = ?, home_id = ? where id = ?",
                    book.getEnterTime(), book.getExitTime(), book.getHome_id(), book.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Book> getBooksByVipId(int vipId) {
        try {
            return qr.query("select * from tb_books where vip_id = ?", new BeanListHandler<>(Book.class), vipId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
